//
//  LYBarHUD.m
//  LYDevelopKit-LYDevelopKit
//
//  Created by 李阳 on 2018/8/20.
//

#import "LYBarHUD.h"
#import <CoreText/CTFontManager.h>

/// 展现类型
typedef NS_ENUM(NSUInteger, LYPresentType)
{
    LYPresentStatus, ///< 仅仅文字
    LYPresentInfo, ///< 展示提醒信息
    LYPresentSuccess, ///< 展示成功信息
    LYPresentError, ///< 展示失败信息
    LYPresentAlert ///< 展示警告信息
};

@interface LYBarHUD ()

@property (nonatomic, weak) UIImageView *imageView;

/// 文字label
@property (nonatomic, weak) UILabel *infoLabel;

/// 屏幕缩放因子 相对于iPhone6
@property (nonatomic, assign) CGFloat screenScale;

@property (nonatomic, assign) NSTimeInterval stayInterval;

@property (nonatomic, copy) void(^completion)(void);

@property (nonatomic, assign, getter=isPresenting) BOOL presenting;


@property (nonatomic, strong) UIImage *infoImage;
@property (nonatomic, strong) UIImage *successImage;
@property (nonatomic, strong) UIImage *errorImage;
@property (nonatomic, strong) UIImage *alertImage;

@end

@implementation LYBarHUD

#pragma mark - Public

+ (void)setFont:(UIFont *)font
{
    [self sharedHUD].infoLabel.font = font;
}
+ (void)setTextColor:(UIColor *)textColor
{
    [self sharedHUD].infoLabel.textColor = textColor;
}
+ (void)setTextAlignment:(NSTextAlignment)textAlignment
{
    [self sharedHUD].infoLabel.textAlignment = textAlignment;
}


+ (void)presentStatus:(NSString *)status
{
    [[self sharedHUD] presentStatus:status];
}

+ (void)presentInfoWithStatus:(NSString *)status
{
    [[self sharedHUD] presentInfoWithStatus:status];
}

+ (void)presentSuccessWithStatus:(NSString *)status
{
    [[self sharedHUD] presentSuccessWithStatus:status];
}

+ (void)presentErrorWithStatus:(NSString *)status
{
    [[self sharedHUD] presentErrorWithStatus:status];
}

+ (void)presentAlertWithStatus:(NSString *)status
{
    [[self sharedHUD] presentAlertWithStatus:status];
}

+ (void)presentCustomWithImage:(UIImage *)image status:(NSString *)status
{
    [[self sharedHUD] presentCustomWithImage:image status:status];
}

+ (void)setStayInterval:(NSTimeInterval)interval
{
    [self sharedHUD].stayInterval = interval;
}

+ (void)setCompletionBlock:(void (^)(void))completion
{
    [self sharedHUD].completion = completion;
}

+ (BOOL)isPresenting
{
    return [self sharedHUD].isPresenting;
}


+ (void)setInfoImage:(UIImage *)image
{
    [self sharedHUD].infoImage = image;
}
+ (void)setSuccessImage:(UIImage *)image
{
    [self sharedHUD].successImage = image;
}
+ (void)setErrorImage:(UIImage *)image
{
    [self sharedHUD].errorImage = image;
}

+ (void)setAlertImage:(UIImage *)image
{
    [self sharedHUD].alertImage = image;
}

#pragma mark - Private

- (void)presentStatus:(NSString *)status
{
    [self presentMessage:status type:LYPresentStatus];
}

- (void)presentInfoWithStatus:(NSString *)status
{
    [self presentMessage:status type:LYPresentInfo];
}

- (void)presentSuccessWithStatus:(NSString *)status
{
    [self presentMessage:status type:LYPresentSuccess];
}

- (void)presentErrorWithStatus:(NSString *)status
{
    [self presentMessage:status type:LYPresentError];
}

- (void)presentAlertWithStatus:(NSString *)status
{
    [self presentMessage:status type:LYPresentAlert];
}

- (void)presentMessage:(NSString *)msg type:(LYPresentType)type
{
    if (self.isPresenting)
    {
        return;
    }
    if (!msg.length)
    {
        return;
    }
    UIColor *imageColor = nil;
    NSString *iconCode = @"";
    UIImage *image = nil;
    switch (type) {
        case LYPresentInfo:
        {
            iconCode = @"\U0000e62b";
            imageColor = [UIColor colorWithRed:0.31 green:0.57 blue:0.93 alpha:1.00];
            image = self.infoImage;
        } break;
            
        case LYPresentSuccess:
        {
            iconCode = @"\U0000e607";
            imageColor = [UIColor colorWithRed:0.47 green:0.76 blue:0.39 alpha:1.00];
            image = self.successImage;
        } break;
            
        case LYPresentError:
        {
            iconCode = @"\U0000e67e";
            imageColor = [UIColor colorWithRed:0.83 green:0.33 blue:0.27 alpha:1.00];
            image = self.errorImage;
        } break;
            
        case LYPresentAlert:
        {
            iconCode = @"\U0000e605";
            imageColor = [UIColor colorWithRed:0.95 green:0.78 blue:0.36 alpha:1.00];
            image = self.alertImage;
        } break;
        default: break;
    }
    
    self.infoLabel.text = msg;
    if (type == LYPresentStatus)
    {
        
    }
    else
    {
        if (image)
        {
            self.imageView.image = image;
        }
        else
        {
            [_imageView removeFromSuperview];
            _imageView = nil;
        }
    }
    
    [self _present];
}


- (void)presentCustomWithImage:(UIImage *)image status:(NSString *)status
{
    if (self.isPresenting)
    {
        return;
    }
    if (!status.length)
    {
        return;
    }
    if (image)
    {
        self.imageView.image = image;
    }
    else
    {
        [_imageView removeFromSuperview];
        _imageView = nil;
    }
    
    self.infoLabel.text = status;
    
    [self _present];
}


- (void)_present
{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self];
    [keyWindow bringSubviewToFront:self];
    
    CGFloat duration = 0.25;
    
    self.presenting = YES;
    [UIView animateWithDuration:duration delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        CGFloat height = self.frame.size.height;
        self.transform = CGAffineTransformMakeTranslation(0, height);
    } completion:^(BOOL finished) {
        //往上平移
        [UIView animateWithDuration:duration delay:self.stayInterval options:UIViewAnimationOptionCurveLinear animations:^{
            //还原
            self.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            !self.completion ?: self.completion();
            [self removeFromSuperview];
            self.presenting = NO;
        }];
    }];
}


#pragma mark - LifeCycle

+ (LYBarHUD *)sharedHUD
{
    static LYBarHUD *hud;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hud = [[[self class] alloc] init];
    });
    return hud;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    CGRect bounds = [[UIScreen mainScreen] bounds];

    frame.size.width = bounds.size.width;
    CGFloat height = bounds.size.height == 812 ? 88 : 64;
    frame.size.height = height;
    frame.origin.y = -height;
    frame.origin.x = 0;
    
    self = [super initWithFrame:frame];
    if (!self) return nil;
    self.screenScale = bounds.size.width / 375.0f;
    [self setup];
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setup];
}

/// 初始化
- (void)setup
{
    _stayInterval = 2.0f;
    
    self.backgroundColor = [UIColor whiteColor];
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(0,1);
    self.layer.shadowOpacity = 0.1;
    
    UILabel *infoLabel = [[UILabel alloc]init];
    
    infoLabel.numberOfLines = 0;
    infoLabel.textColor = [UIColor blackColor];
    
    CGFloat fontSize = round(14 * _screenScale * 10) / 10;

    infoLabel.font = [UIFont systemFontOfSize:fontSize];
    infoLabel.textAlignment = NSTextAlignmentLeft;
    
    [self addSubview:infoLabel];
    _infoLabel = infoLabel;
    
    NSBundle *mainBundle = [NSBundle bundleForClass:[LYBarHUD class]];
    NSURL *bundleUrl = [mainBundle URLForResource:@"LYDevelopKit" withExtension:@"bundle"];
    NSBundle *bundle = [NSBundle bundleWithURL:bundleUrl];
    NSBundle *hudBundle = [NSBundle bundleWithURL:[bundle URLForResource:@"BarHUD" withExtension:@"bundle"]];
    
    _alertImage = [UIImage imageWithContentsOfFile:[self pathForImageNamed:@"alert" inBundle:hudBundle]];
    _infoImage = [UIImage imageWithContentsOfFile:[self pathForImageNamed:@"info" inBundle:hudBundle]];
    _errorImage = [UIImage imageWithContentsOfFile:[self pathForImageNamed:@"error" inBundle:hudBundle]];
    _successImage = [UIImage imageWithContentsOfFile:[self pathForImageNamed:@"success" inBundle:hudBundle]];
}

- (NSString *)pathForImageNamed:(NSString *)imageName inBundle:(NSBundle *)bundle
{
    CGFloat screenScale = [UIScreen mainScreen].scale;
    if (screenScale > 2)
    {
        imageName = [imageName stringByAppendingString:@"@3x"];
    }
    else
    {
        imageName = [imageName stringByAppendingString:@"@2x"];
    }
    return [bundle pathForResource:imageName ofType:@"png"];
}

- (void)layoutSubviews
{
    CGFloat margin = 15 * _screenScale;
    CGFloat bottomSpace = 10 * _screenScale;
    CGFloat left = margin;
    CGFloat height = self.frame.size.height;
    CGFloat width = self.frame.size.width;
    CGFloat iconH = 0;
    
    if (_imageView)
    {
        [_imageView sizeToFit];
        CGRect frame = _imageView.frame;
        frame.origin = CGPointMake(left, height - frame.size.height - bottomSpace);
        _imageView.frame = frame;
        left += (frame.size.width + 8 * _screenScale);
        iconH = frame.size.height;
    }
    
    [_infoLabel sizeToFit];
    CGRect infoFrame = _infoLabel.frame;
    infoFrame.size.width = width - left - margin;
    infoFrame.origin.x = left;
    CGFloat infoLabeT = height - infoFrame.size.height - bottomSpace;
    if (iconH)
    {
        infoLabeT -= (iconH - infoFrame.size.height) * 0.5;
    }
    
    infoFrame.origin.y = infoLabeT;
    _infoLabel.frame = infoFrame;
}


#pragma mark - Getter & Setter
- (UIImageView *)imageView
{
    if (_imageView) return _imageView;
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:imageView];
    _imageView = imageView;
    return _imageView;
}

@end
